package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.entity.FileEntity;
import com.docmgmt.mvp.entity.UserEntity;
import com.docmgmt.mvp.exception.UnauthorizedException;
import com.docmgmt.mvp.mapper.FileMapper;
import com.docmgmt.mvp.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试上传文档 Controller
 *
 * 用于测试查询用户有权限的文档
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/test")
@RequiredArgsConstructor
@Tag(name = "测试接口", description = "用于测试的临时接口")
public class TestUploadController {

    private final FileMapper fileMapper;
    private final UserMapper userMapper;

    /**
     * 查询用户有权限的文档
     *
     * GET /api/v1/test/accessible-docs
     */
    @GetMapping("/accessible-docs")
    // 移除了 @PreAuthorize("hasAuthority('ai:chat')") 注解，允许任何认证用户访问
    @Operation(summary = "查询用户有权限的文档", description = "查询当前用户有权限访问的文档")
    public Result<Map<String, Object>> getAccessibleDocs() {

        // 获取当前用户 ID
        Long userId = getCurrentUserId();

        // 获取用户的部门 ID
        UserEntity user = userMapper.selectById(userId);
        if (user == null) {
            throw new UnauthorizedException("用户不存在");
        }
        Long deptId = user.getDepartmentId();

        log.info("========================================");
        log.info("查询用户有权限的文档");
        log.info("用户 ID: {}", userId);
        log.info("用户名: {}", user.getUsername());
        log.info("部门 ID: {}", deptId);
        log.info("========================================");

        try {
            // 查询用户有权限的文档
            List<FileEntity> accessibleFiles = fileMapper.selectAccessibleDocsForGlobal(userId, deptId);

            log.info("查询到文件数量: {}", accessibleFiles.size());

            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("totalCount", accessibleFiles.size());
            response.put("files", accessibleFiles);

            // 显示文件列表
            log.info("========================================");
            log.info("用户有权限的文档列表:");
            log.info("========================================");

            int index = 1;
            for (FileEntity file : accessibleFiles) {
                log.info("{}. ID={}, 名称={}, 隐私级别={}, RAGFlow Doc ID={}",
                        index++,
                        file.getId(),
                        file.getFileName(),
                        file.getPrivacyLevel(),
                        file.getRagflowDocId());
            }

            log.info("========================================");
            log.info("✅ 查询完成，共 {} 个文档", accessibleFiles.size());
            log.info("========================================");

            return Result.success(response);

        } catch (Exception e) {
            log.error("❌ 查询失败: {}", e.getMessage(), e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 从 Spring Security 上下文获取当前用户 ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("未登录或认证已过期");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        }

        throw new UnauthorizedException("无效的认证信息");
        }
}